package org.itboys.seller;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.seller.entity.SiteUser;
import org.itboys.seller.mapper.CashFlowMapper;
import org.itboys.seller.meta.CashFlow;
import org.itboys.seller.meta.CashFlowExample;
import org.itboys.seller.service.CaliforniaSiteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hzliangchong1@corp.netease.com
 *         Date 2017/4/22.
 */
@RestController
@RequestMapping("/achievement")
public class AchievementController extends BaseController {

    @Autowired
    private CaliforniaSiteUserService californiaSiteUserService;
    @Resource
    private CashFlowMapper cashFlowMapper;

    /**
     * 进入登入页面
     */
    @RequestMapping("/toSelfVM")
    public ModelAndView toSelfVM(Model model,HttpServletRequest request){
        //登入过的用户名一般放在cookieli里
        return new ModelAndView("/ace/achievement/self-list");
    }

    @RequestMapping("/toServerVM")
    public ModelAndView toServerVM(Model model,HttpServletRequest request){
        //登入过的用户名一般放在cookieli里
        return new ModelAndView("/finance/server-list");
    }

    @RequestMapping("/toPassSetVM")
    public ModelAndView toPassSetVM(Model model,HttpServletRequest request){
        //登入过的用户名一般放在cookieli里
        return new ModelAndView("/ace/achievement/passwordset");
    }

    @RequestMapping("/selfList")
    public void selfList(String startDate, String endDate, HttpServletRequest request, HttpServletResponse response) {
        Long proUserId = AdminSessionHolder.getAdminUserId();
        List<SiteUser> users = californiaSiteUserService.getUsersByRecAndType(proUserId, 0);
        if (CollectionUtils.isEmpty(users)) {
            JsonPageUtils.renderJsonPage(0L, Lists.newArrayList(), response);
            return;
        }
        List<AchievementDto> dtos = getAchievements(users, request, startDate, endDate);
        JsonPageUtils.renderJsonPage(dtos.size() > 0 ? (long)dtos.get(0).getCount() : 0, dtos, response);
    }

    @RequestMapping("/serverList")
    public void serverList(@RequestParam(value = "memberType", defaultValue = "1") int memberType,
                           String startDate, String endDate, HttpServletRequest request, HttpServletResponse response) {
        List<SiteUser> users = californiaSiteUserService.getUsersByRecAndType(0, memberType);
        if (CollectionUtils.isEmpty(users)) {
            JsonPageUtils.renderJsonPage(0L, Lists.newArrayList(), response);
            return;
        }
        int pageNo = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("rows"));
        int start = (pageNo - 1) * limit;
        int count = users.size();
        users = users.subList(Math.min(start, users.size()), Math.min(start + limit, users.size()));
        List<AchievementDto> dtos = Lists.newArrayList();
        List<SiteUser> cityUsers;
        for (SiteUser user : users) {
            cityUsers = californiaSiteUserService.getUsersByRecAndType(user.getUserId(), 0);
            List<Long> userIds = cityUsers.stream().map(SiteUser::getUserId).collect(Collectors.toList());
            AchievementDto dto = new AchievementDto();
            dto.setUserId(user.getUserId());
            dto.setPhone(user.getPhone());
            dto.setUserName(user.getMemberName());
            dto.setRealName(user.getRealName());
            dto.setArea(user.getArea());
            if (CollectionUtils.isEmpty(userIds)) {
                dto.setAmount(0);
            } else {
                CashFlowExample example = new CashFlowExample();
                CashFlowExample.Criteria criteria = example.createCriteria();
                criteria.andUserIdIn(userIds).andStateEqualTo(1);
                if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        criteria.andUpdateTimeBetween(sdf.parse(startDate + " 00:00:00"), sdf.parse(endDate + " 23:59:59"));
                    } catch (ParseException e) {
                        logger.error("时间转换错误");
                    }
                }
                List<CashFlow> cashFlows = cashFlowMapper.selectByExample(example);
                dto.setAmount(cashFlows.stream().mapToInt(CashFlow::getAmount).sum());
            }
            dtos.add(dto);
        }
        JsonPageUtils.renderJsonPage((long)count, dtos, response);
    }

    private List<AchievementDto> getAchievements(List<SiteUser> users, HttpServletRequest request, String startDate, String endDate) {
        List<Long> userIds = users.stream().map(SiteUser::getUserId).collect(Collectors.toList());
        Map<Long, SiteUser> id2UserMap = users.stream().collect(Collectors.toMap(SiteUser::getUserId, p -> p));
        int pageNo = Integer.parseInt(request.getParameter("page"));
        int limit = Integer.parseInt(request.getParameter("rows"));
        CashFlowExample example = new CashFlowExample();
        CashFlowExample example1 = new CashFlowExample();
        CashFlowExample.Criteria criteria = example.createCriteria();
        CashFlowExample.Criteria criteria1 = example1.createCriteria();
        criteria.andUserIdIn(userIds).andStateEqualTo(1);
        criteria1.andUserIdIn(userIds).andStateEqualTo(1);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                criteria.andUpdateTimeBetween(sdf.parse(startDate + " 00:00:00"), sdf.parse(endDate + " 23:59:59"));
                criteria1.andUpdateTimeBetween(sdf.parse(startDate + " 00:00:00"), sdf.parse(endDate + " 23:59:59"));
            } catch (ParseException e) {
                logger.error("时间转换错误");
            }
        }
        int start = (pageNo - 1) * limit;
        example.setLimitStart(start);
        example.setLimitEnd(start + limit);
        example.setOrderByClause("update_time desc");
        List<CashFlow> cashFlows = cashFlowMapper.selectByExample(example);
        List<AchievementDto> dtos = Lists.newArrayList();
        for (CashFlow cashFlow : cashFlows) {
            AchievementDto dto = new AchievementDto();
            dto.setUserId(cashFlow.getUserId());
            dto.setAmount(cashFlow.getAmount());
            dto.setTime(TimeUtils.format(cashFlow.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
            SiteUser user = id2UserMap.get(cashFlow.getUserId());
            dto.setPhone(user.getPhone());
            dto.setUserName(user.getMemberName());
            dto.setRealName(user.getRealName());
            dto.setArea(user.getArea());
            dtos.add(dto);
        }
        cashFlows = cashFlowMapper.selectByExample(example1);
        int total = cashFlows.stream().mapToInt(CashFlow::getAmount).sum();
        for (AchievementDto dto : dtos) {
            dto.setTotalAmount(total);
            dto.setCount(cashFlows.size());
        }
        return dtos;
    }

    /**
     * 修改密码
     */
    @RequestMapping("/passwordset")
    public void passwordset(String prePass, String newPass,
                          HttpServletRequest request, HttpServletResponse response) {
        Long proUserId = AdminSessionHolder.getAdminUserId();
        SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(proUserId);
        if (proUser == null) {
            AjaxUtils.renderText(response, "用户不存在");
            return;
        }
        if(!StringUtils.equals(proUser.getPassword(), Digests.md5(prePass))){
            AjaxUtils.renderText(response, "旧密码不正确");//密码不正确
            return ;
        }
        proUser.setPassword(Digests.md5(newPass));
        californiaSiteUserService.update(proUser);
        AjaxUtils.renderText(response, CommonConstants.SUCCESS);
    }
}
